<template>
  <div class="action-btn-wp">
    <el-popover
        placement="left"
        width="690"
        trigger="click">
      <el-button type="primary" size="small" slot="reference" @click.stop.prevent="handelClick">处理退还</el-button>

      <div class="return-box" v-loading="loading">
        <header>
          处理退还
        </header>
        <div class="body">
          <el-form ref="form">
            <el-form-item class="form-item">
              <el-checkbox v-model="checked">已收到退还设备</el-checkbox>
              <el-tooltip effect="dark" content='物流信息显示已到达,如果您未收到货,请在已退还页面中点击"未收到货"' placement="bottom">
                <i class="icon fa fa-question-circle-o"></i>
              </el-tooltip>
            </el-form-item>
            <el-form-item class="form-item" label="损坏情况">
              <el-radio-group v-model="damage" @change="handleChange">
                <el-radio :label="false">无损坏</el-radio>
                <el-radio :label="true">需要赔偿</el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-show="damage">
              <el-form-item class="form-item">
                <div class="tip"><i class="fa fa-circle"></i>赔偿相关事宜建议先与用户进行协商沟通</div>
              </el-form-item>
              <el-form-item class="form-item" v-for="(item, index) in damageList" :key="index">
                <span>损坏情况{{index+1}}:</span>
                <el-select v-model="item.describe" placeholder="请选择损坏情况">
                  <el-option
                      v-for="(compensate,i) in compensateItems"
                      :key="i"
                      :label="compensate.name"
                      :value="compensate.name"
                      :disabled="isContains(compensate.name,selectedDamages)"
                      >
                  </el-option>
                </el-select>

                <!--<el-input placeholder="请输入损坏情况" v-model="item.describe" style="width: 230px;"></el-input>-->

                <span style="margin-left: 15px;">赔偿金额(元):</span>
                <el-input-number :min="0" v-model="item.money" @change="handleInputNumberChange"></el-input-number>
                <el-tooltip v-if="index==0" class="item" effect="dark" content="赔偿金额建议整数" placement="right">
                  <i class="icon el-icon-warning"></i>
                </el-tooltip>
                <i v-if="index!=0" class="el-icon-delete icon" title="删除该项" @click.stop.prevent="removeDamageItem(index)"></i>
              </el-form-item>
              <el-form-item class="form-item">
                <el-button type="text" icon="plus" @click.stop.prevent="addDamageItem()">新增赔偿项</el-button>
              </el-form-item>
              <el-form-item class="form-item" style="margin-top: 30px;">
                <div class="image-list-wp">
                  <span class="label">图片凭证:(最多5张)</span>
                  <resource-manager type="cards" dir="evidence" :cards-num="5" :modal="false" @insert-success="insertImgsSuccess"></resource-manager>
                </div>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <footer>
          <div class="btn-wp">
            <el-button class="btn" type="primary" @click="onSubmit()" :disabled="!checked" :loading="submiting">确定</el-button>
            <el-button class="btn" @click="cancelSubmit()">取消</el-button>
          </div>
        </footer>
      </div>
    </el-popover>
  </div>
</template>

<script>
  import ResourceManager from '@/components/ResourceManager';

  import {orderReturnDispose,getCompensateItems} from '@/api/order';
  import {showMessage} from '@/utils/message';
  import {osshost} from '@/api/util/fetch';

  export default {
    name: 'actionReturned', //处理退还
    components:{
      'resource-manager':ResourceManager,
    },
    props:{
      scope:{
        type:Object,
        default:()=>{},
      },
      scopeId:{
        type:String,
        default:'id'
      }
    },
    data(){
      return {
        checked:false, //是否收到货
        damage:false, //是否损坏
        damageList:[
          {
            describe:'', //损坏项目
            money:0, //赔偿金额
          }
        ], //赔偿项目
        imageList:[
          /*{
            url:'',
          }*/
        ],
        submiting:false, //正在提交
        compensateItems:[], //损坏项
        loading:false,
      }
    },
    computed:{
      //提交的赔偿项目,金额是分
      damageSituationList()
      {
         let list = [];
         this.damageList.forEach(item=>{
            list.push({
              describe:item.describe,
              money:item.money*100,
            })
         });

         return list;
      },
      selectedDamages() //已选择的损坏项目
      {
         let arr = [];
         this.damageList.forEach(item=>{
           arr.push(item.describe);
         });

         return arr;
      },
    },
    methods: {
      handelClick()
      {
        //关闭所有pop，防止窗口重叠
        document.querySelector("#app").click();

        let row = this.scope.row || {};
        let data = {
          id:row[this.scopeId],
        };

        this.loading = true;

        getCompensateItems(data).then(resp=>{

          this.compensateItems = resp.data || [];
          this.loading = false;

        }).catch(err=>{

          this.loading = false;

        });

      },
      onSubmit() //处理退还
      {
        if(!this.checked || this.submiting)
        {
          return;
        }

        let index = this.scope.index;
        let rows = this.scope.rows;

        //无损坏
        if(!this.damage)
        {
          this.$confirm('请确认商品无损坏，是否继续?', '处理退还', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            let data = {
              id:this.scope.row[this.scopeId],
              isReceiveDevice:true,
              damageSituation:'nodamage', //损坏情况: nodamage、无损坏 compensate、须赔偿
              damageSituationList:[],
              image:[],
            };

            this.submiting = true;

            orderReturnDispose(data).then(resp=>{

              showMessage({title:'处理退还成功',type:'success'});

              this.submiting = false;

              rows.splice(index,1);
              this.$emit('returned-success');

              this.resetdata();

            }).catch(err=>{
              this.submiting = false;
            });

          }).catch(() => {


          });
        }
        else //有损坏
        {

          if(this.damageList.length >=1 && this.damageList[0].describe.trim().length <=0)
          {
            this.$message({
              message: '请选择损坏情况',
              type: 'error',
              duration: 5000
            });

            return;
          }

          //检查损坏金额是否正确
          if(this.damageList.some(item=>{
            return !/^[0-9]*[1-9][0-9]*$/.test(item.money);
            }))
          {
            this.$message({
              message: '请检查赔偿金额,必须为整数',
              type: 'error',
              duration: 5000
            });
            return;
          }

          if(this.imageList.length <=0)
          {
            this.$message({
              message: '请至少上传一张图片凭证',
              type: 'error',
              duration: 5000
            });

            return;
          }

          let data = {
            id:this.scope.row[this.scopeId],
            isReceiveDevice:true,
            damageSituation:'compensate', //损坏情况: nodamage、无损坏 compensate、须赔偿
            damageSituationList: this.damageSituationList,
            image:this.imageList,
          };

          this.submiting = true;

          orderReturnDispose(data).then(resp=>{

            showMessage({title:'赔偿申请提交成功',message:'系统已通知用户进行赔偿，详情可在待赔偿页面查看！',type:'success'});

            document.querySelector("#app").click();
            this.submiting = false;

            rows.splice(index,1);

            this.$emit('returned-success');
            this.resetdata();

          }).catch(err=>{

            this.submiting = false;

          });

        }

      },
      resetdata()
      {
        this.checked=false;
        this.damage = false;
        this.damageList = [];
        this.imageList = [];
        this.compensateItems = [];

        this.$refs['form'].resetFields();

      },
      cancelSubmit()
      {
        document.querySelector("#app").click();
      },
      handleChange(value) //损坏情况
      {

      },
      handleInputNumberChange(newValue, oldValue) //计数器改变
      {

      },
      addDamageItem()
      {
        this.damageList.push({
          describe:'', //损坏项目
          money:0, //赔偿金额
        });
      },
      removeDamageItem(index)
      {
        this.damageList.splice(index,1);
      },
      insertImgsSuccess(files)
      {
        this.imageList = files;
      },
      isContains(item,arr) //元素是否包含在数组中
      {
        let i = arr.length;
        while (i--) {
          if (arr[i] === item) {
            return true;
          }
        }
        return false;
      },
    },
  }
</script>
<style lang="scss" scoped>
  @import "../../../styles/mixin";
  .return-box
  {
    > header
    {
      padding: 10px;
      border-bottom: 1px solid #eee;
      text-align: center;

    }

    > .body
    {
      padding: 10px;

      .form-item
      {
         margin-bottom: 10px;
      }
      .tip
      {
        color: #999;

        .fa
        {
           color: #FFA500;
           font-size: 12px;
           margin-right: 8px;
        }
      }

      .icon
      {
        font-size: 20px;
        vertical-align: middle;
        padding: 2px;
        color: #8492a6;
        cursor: pointer;
        margin-left: 5px;
        &:hover
        {
          color: #1c8de0;
        }
      }

      .image-list-wp
      {
        @include clearfix;
        .label
        {
          float: left;
          width: 60px;
          font-size: 14px;
          line-height: 1.5;
        }

        .image-wp
        {
          float: left;
          position: relative;
          margin-left: 15px;
          width: 100px;
          height: 100px;
          border: 1px dashed #d1dbe5;
          border-radius: 6px;
          text-align: center;

          .img-wp
          {
            width: 100%;
            height: 100%;
            text-align: center;

            > img
            {
              width: 100%;
              height: 100%;
              display: block;
            }
          }

          .remove-icon
          {
            position: absolute;
            border-radius: 50%;
            font-size: 20px;
            background: #fff;
            border: 1px solid #8c939d;
            color: #8c939d;
            width: 30px;
            height: 30px;
            text-align: center;
            line-height: 26px;
            right: -10px;
            top:-10px;
            z-index: 2;

            &:hover
            {
              color: #20a0ff;
              border-color: #20a0ff;
            }
          }

        }


      }

    }

    > footer
    {
      padding: 10px;
      border-top: 1px solid #eee;
      .btn-wp
      {
        text-align: center;
        .btn
        {
          margin: 0 15px;
        }
      }
    }
  }
</style>
